import { insertPagesCssLink } from "../../util/insert-style.js"
import { swiperCreater } from "../../component/swiper/index.js"
import { fetchMenu } from "./api.js"
import { createCard } from "../../component/cuisines-card/index.js"
import { add_order, order_tage } from "../../util/order-control.js"


export async function createHome() {
    insertPagesCssLink('home')

    let menu = await fetchMenu()
    let order = JSON.parse(localStorage.getItem('order')||"[]") || []
    
    if(order.length>0){
        order.forEach(item => {
            menu.forEach(i=>{
                if(i.id === item.id){
                    i.count = item.count
                }
            })
        })
    }
    
    menu = [...menu, ...menu, ...menu]

    // 创建轮播图
    const images = menu.map(item => ({
        url: item.cuisineImgPath, content: item.cuisineDesc
    }));
    const swiper = swiperCreater(images, { showNavButtons: true, showNavDots: true, showContent: true });


    const content = $(/*HTML*/`
        <div class="home-container">
            <div class="swiper-wrapper">${swiper.outerHTML}</div>
            <div class="menu">
                ${menu.map((item, index) => createCard({
        name: item.cuisineName,
        image: item.cuisineImgPath,
        description: item.cuisineDesc,
        price: item.cuisinePrise, // 假设菜单项中有价格字段
        index,
        count:item.count
        }, '200px', '340px')).join('')}
            </div>
        </div>
    `); // 返回一个Promise

    function update_nav(){
        if($(".nav-order").find("span").length == 0){
            let nav = $(`<span id="order-badge" class="position-absolute translate-middle badge rounded-pill bg-danger">${order_tage()}</span>
                            <a class="nav-link" href="#">
                          我的订单
                            </a>`)
            $(".nav-order").html(nav)
        }
    }
    function update_card(name,count){
        Array.from($(".card-title")).forEach(i=>{
            if($(i).text()==name){
                $(i).parent().find("span").text(count)
            }
        })
       
        
        
    }

    $("#add", content).on("click", async function () {
        let index = $(this).attr("data-i");
        menu[index].count?menu[index].count++:menu[index].count = 1
        $(this).next("span").text(menu[index].count)
       add_order(menu[index],true)

        update_nav()
        update_card(menu[index].cuisineName,menu[index].count)
        
        
    })
    $("#reduction", content).on("click", async function () {
        let index = $(this).attr("data-i");
        if(menu[index].count&&menu[index].count>0)menu[index].count--
       
        
        $(this).prev("span").text(menu[index].count)
        add_order(menu[index],false)
        update_nav()
        update_card(menu[index].cuisineName,menu[index].count)
    })

    return content
}

export default createHome